package com.buer.storage.common.aspect;


import com.buer.storage.common.constant.Constant;
import com.buer.storage.common.eumn.RequestType;
import com.buer.storage.common.eumn.ResultEnum;
import com.buer.storage.common.handle.BaseException;
import com.buer.storage.common.holder.RequestTypeHolder;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * 登录拦截
 */
@Aspect
@Component
public class LoginAuth {
    private static final Logger logger = LoggerFactory.getLogger(LoginAuth.class);

    @Autowired
    private HttpServletRequest request;


    @Pointcut("@annotation(com.buer.storage.common.annotation.Login)")
    public void AuthPointCut() {
    }

    @Before("AuthPointCut()")
    public void LoginBefore(JoinPoint joinPoint) throws Throwable {
        String appTypeStr = request.getHeader(Constant.REQUEST_TYPE);
        logger.info(joinPoint.getTarget() + " " + joinPoint.getSignature().getName() + "  request header contains requestType: " + appTypeStr);
        //step1 验证请求是否合法
        checkLegality(appTypeStr);
        //step2 存入本地线程池
        RequestTypeHolder.setRequestTypeHolder(appTypeStr);
    }

    private void checkLegality(String appTypeStr) {
        if (StringUtils.isBlank(appTypeStr)) {
            logger.error("requestType不能为空，请求不合法");
            throw new BaseException(ResultEnum.ILLEGAL_ERROR);
        }
        try {
            RequestType requestType = RequestType.valueOf(appTypeStr);
        }catch (Exception e){
            throw new BaseException(ResultEnum.ILLEGAL_ERROR);
        }

    }


    @After("AuthPointCut()")
    public void methodAfter(JoinPoint joinPoint){
        RequestTypeHolder.clearRequestTypeHolder();
    }


}